import { login, logout, getInfo } from '@/api/login'
import store from 'store'
export default {

    state: {
        token: store.get("token") === undefined ? "" : store.get("token"),
        name: '',
        avatar: '',
        roles: []
    },
    mutations: {
        SET_TOKEN(state: any, token: string) {
            state.token = token
            store.set("token", token)
        },
        SET_NAME: (state: any, name: string) => {
            state.name = name
        },
        SET_AVATAR: (state: any, avatar: string) => {
            state.avatar = avatar
        },
        SET_ROLES: (state: any, roles: Array<string>) => {
            state.roles = roles
        }
    },
    actions: {
        async Login({ commit }: any, userInfo: any) {
            const username = userInfo.username.trim();
            const { data } = await login(username, userInfo.password)
            commit("SET_TOKEN",data.tokenHead+" "+data.token)
        },
        async Logout({ commit }: any) {
            await logout()
            commit("SET_TOKEN", "")
        },
        async GetInfo({ commit }: any) {
            const { data } = await getInfo()
            if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
                // console.log(data.roles);
                commit('SET_ROLES', data.roles)
            } else {
                Promise.reject('getInfo: roles must be a non-null array !')
            }
            commit('SET_NAME', data.username)
            commit('SET_AVATAR', data.icon)
            return data;
        }
    }
}